<template>
	<el-drawer title="我是里面的" :append-to-body="true" size="60%" :visible.sync="amapDialog" :show="show" @close="click"
		:with-header="false">

		<div>
			<panle title='标注地图位置' content="请点击/拖动图标到正确的位置，再点击底部确定按钮."></panle>
			<div>
				<div class="coord-picker">
					<div class="map-container">
						<amap cache-key="coord-picker-map" mmap-style="amap://styles/whitesmoke" async
							:center.sync="center" :zoom.sync="zoom" is-hotspot @click="onMapClick">
							<amap-satellite-layer :visible="satellite" />

							<amap-marker v-if="position" :position.sync="position" draggable />
							<el-card class="result-panel">
								<div slot="header" class="clearfix">
									<div v-if="mode === 'search'">
										<el-autocomplete v-model="query" :fetch-suggestions="autoComplete">
											<el-button slot="append" @click="search(true)" :disabled="!query">搜索
											</el-button>
										</el-autocomplete>
									</div>
									<div v-if="mode === 'result'">
										<div class="search-bar">
											<i class="el-icon-caret-left" circle @click="reset"
												style="margin-right: 6px;"></i>
											<span class="text">搜索 {{ query }} 共
												{{ searching ? '...' : total }} 条结果</span>
										</div>
									</div>


								</div>
								<div v-if="mode === 'result'">
									<div class="block">
										<el-pagination layout="prev, pager, next" v-if="total > 0" v-model="pageIndex"
											:page-size="pageSize" :total="total" small>
										</el-pagination>
									</div>
									<el-scrollbar style="height:300px;">
										<div class="list-resu">



											<div class="text item" v-for="(item,index) in results" :key="index"
												@click="focus(item)">
												<span class="font1">{{item.address}}</span>
												<span class="font2">{{ item.name }}</span>
											</div>

										</div>
									</el-scrollbar>

								</div>
							</el-card>

							<el-form class="info " :inline="true">
								<el-form-item label="坐标">
									<el-input v-model="positionText" size="mini"></el-input>
								</el-form-item>
								<el-form-item label="卫星图">
									<el-switch v-model="satellite" active-color="#13ce66" inactive-color="#ff4949">
									</el-switch>
								</el-form-item>
							</el-form>

						</amap>
					</div>
				</div>
			</div>
			<div class="drawer__footers" style="display: flex;">
				
				<el-button type="primary" @click="sureSelect ">
					 确 定</el-button>
			</div>
		</div>
	</el-drawer>
</template>

<script>
	import {
		loadAmap,
		loadPlugins
	} from '@amap/amap-vue';
	import Panle from '@/components/Panle';
	export default {
		name: 'select-amap',
		components: {
			Panle
		},
		data() {
			return {
				amapDialog: false,
				mode: 'search',
				center: null,
				zoom: 15,
				query: '',
				searching: false,
				tips: [],
				results: [],
				position: null,
				pageIndex: 1,
				pageSize: 10,
				total: 0,
				satellite: false,
				address:'',

			}
		},
		props: {
			show: {
				type: Boolean,
				default: false
			},
		},
		watch: {
			show() {
				this.amapDialog = this.show;

			},
			pageIndex(value) {
				this.$ready.then(() => {
					this.ps.setPageIndex(value);
					this.search(false);
				});
			},
		},
		computed: {
			wrapper() {
				return this.$refs.wrapper;
			},
			positionText() {
				//console.log(this.position);
				if (!this.position) return '';
				this.regeoCode();
				return `${this.position[0]}, ${this.position[1]}`;
			},
		},
		created() {
			this.$ready = new Promise(async resolve => {
				const AMap = await loadAmap();
				await loadPlugins(['AMap.PlaceSearch', 'AMap.AutoComplete','AMap.Geocoder']);

				this.ps = new AMap.PlaceSearch({
					pageSize: this.pageSize,
				});
				this.ac = new AMap.AutoComplete();

                this.ag = new AMap.Geocoder();
				resolve();
			});
		},
		methods: {
			click() {
				this.$emit('update', this.show)


			},
			onMapClick(e) {
				if (e.lnglat) {
					this.position = [e.lnglat.lng, e.lnglat.lat];
					this.regeoCode();
				} else {
					this.position = null;
				}
				
			},
			 regeoCode() {
			        this.ag.getAddress(this.position,(status,result)=>{
						if (status === 'complete'&&result.regeocode) {
						    this.address = result.regeocode.formattedAddress;
							console.log(this.address);
						    //document.getElementById('address').value = address;
						}else{
						   // log.error('根据经纬度查询地址失败')
						}
					});
			       
			    },
			async search(clear = false) {
				this.mode = 'result';
				await this._ready;

				if (clear) {
					this.results = [];
					this.total = 0;
					this.pageIndex = 1;
					this.ps.setPageIndex(1);
				}

				this.searching = true;
				const {
					query
				} = this;
				this.ps.search(query, (status, result) => {
					this.searching = false;
					if (query !== this.query) return;
                      
					if (status === 'complete' && result.poiList) {
						this.results = result.poiList.pois;
						this.total = result.poiList.count;
					} else {
						this.results = [];
						this.total = 0;
					}
				});
			},
			async autoComplete(kw, cb) {
				if (!kw) {
					this.tips = [];
				} else {
					this.ac.search(kw, (status, result) => {

						if (kw !== this.query) return;

						if (status === 'complete' && result.tips) {
							let res = [];
							result.tips.forEach((it) => {
								res.push({
									"value": it.name
								});
							})
							this.tips = Array.from(new Set(result.tips.map(tip => tip.name)));
							cb(res);
						} else {
							this.tips = [];
						}
					});
				}
			},

			focus(poi) {
				const pos = [poi.location.lng, poi.location.lat];
				this.position = [...pos];
				this.center = [...pos];
				console.log(poi);
				this.address = poi.address;
				//this.regeoCode();
			},
			reset() {
				this.ps.setPageIndex(1);
				this.results = [];
				this.tips = [];
				this.total = 0;
				this.mode = 'search';
			},
			sureSelect: function() {
			       if(!this.position){
					   this.$message({
					   	type: 'error',
					   	message: '请选择地点'
					   });
					   return false;
				   }
				   
				   
				   
				   
				this.$emit('selectSure', this.position,this.address);
			
				this.click();
				//this.selectDate = [];
				//this.init();
			
			},
		}
	}
</script>

<style lang="scss">
	.map-container {
		width: 100%;
		height: 600px;
	}

	.result-panel {
		position: absolute;
		left: 10px;
		top: 10px;
		width: 320px;
		display: flex;
		flex-direction: column;

		.search-bar {
			display: flex;
			align-items: center;

			.text {
				text-overflow: ellipsis;
				flex: 1;
				overflow: hidden;
				white-space: nowrap;
			}
		}

		.result-list.ant-list-loading {
			min-height: 100px;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.item {
			border-bottom: #dbdbdb solid 1px;
			min-height: 50px;
			display: flex;
			justify-content: flex-start;
			flex-direction: column;
			margin-bottom: 16px;

			.font1 {
				color: rgba(0, 0, 0, .85);
				font-size: 16px;
				line-height: 24px;
				font-weight: 600;
				margin-bottom: 12px;
			}

			.font2 {
				font-size: 14px;
				line-height: 22px;
				color: rgba(0, 0, 0, .45);
				margin-bottom: 10px;
			}
		}

		.el-card__body {
			padding: 0 !important;
			max-height: 300px;
		}

		.el-card__header {
			padding: 6px 20px !important;
		}

		.block {

			display: flex;
			justify-content: center;
		}

		.list-resu {
			padding: 0px 20px;
		}


	}

	.info {
		position: absolute;
		right: 10px;
		top: 10px;
		padding-left: 24px;
		background-color: #FFFFFF;

		.el-form-item {
			margin: 0 !important;
		}
	}
	.drawer__footers {
		display: flex;
		margin-left: 20px;
		margin-right: 20px;
		justify-content: flex-end;
		margin-top: 20px;
		.el-button{
			width: 20%;
		}
	}
</style>
